package com.logistics.controller;

import com.logistics.common.Result;
import com.logistics.entity.SysUser;
import com.logistics.mapper.SysUserMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 初始化控制器（仅用于开发环境）
 */
@RestController
@RequestMapping("/init")
public class InitController {
    
    private final SysUserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    
    public InitController(SysUserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }
    
    /**
     * 初始化用户密码
     * 访问此接口将重置测试账号的密码
     */
    @GetMapping("/password")
    public Result<Map<String, String>> initPassword() {
        Map<String, String> result = new HashMap<>();
        
        try {
            // 生成 BCrypt 加密密码
            String adminPassword = passwordEncoder.encode("admin123");
            String tenantPassword = passwordEncoder.encode("123456");
            
            // 更新 admin 密码
            SysUser admin = userMapper.selectById(1L);
            if (admin != null) {
                admin.setPassword(adminPassword);
                userMapper.updateById(admin);
                result.put("admin", "密码已重置为: admin123");
            } else {
                result.put("admin", "用户不存在，请先执行 SQL 脚本");
            }
            
            // 更新 tenant001 密码
            SysUser tenant = userMapper.selectById(2L);
            if (tenant != null) {
                tenant.setPassword(tenantPassword);
                userMapper.updateById(tenant);
                result.put("tenant001", "密码已重置为: 123456");
            } else {
                result.put("tenant001", "用户不存在，请先执行 SQL 脚本");
            }
            
            result.put("adminPasswordHash", adminPassword);
            result.put("tenantPasswordHash", tenantPassword);
            
            return Result.success("密码初始化成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("密码初始化失败: " + e.getMessage());
        }
    }
}

